#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <sys/select.h>
#include <cstring>
#include "Sock.hpp"

const static uint16_t default_port = 8889;
const static int defaultfd = -1;
const static int defaultevent = 0;

#define FD_READ (0x1 << 1)
#define FD_WRITE (0x1 << 2)
#define FD_EXCEPT (0x1 << 3)

struct FdEvent
{
    int _fd;
    int _event;
    std::string _client_ip;
    uint16_t _client_port;
};

class SelectServer
{
    const static int N = sizeof(fd_set) * 8;

public:
    SelectServer(uint16_t port = default_port)
        : _port(port)
    {
    }

    void Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        for (int i = 0; i < N; i++)
        {
            _fdarry[i]._fd = defaultfd;
            _fdarry[i]._event = 0;
            _fdarry[i]._client_ip = "";
            _fdarry[i]._client_port = 0;
        }
    }

    void Start()
    {
        // 保存监听套接字
        _fdarry[0]._fd = _listensock.GetFd();
        _fdarry[0]._event = FD_READ;
        _fdarry[0]._client_ip = "127.0.0.1";
        _fdarry[0]._client_port = 8888;
        while (true)
        {
            // 因为rfds是输入输出型参数，注定了每次都要对rfds进行重新写入
            // 因为服务器在运行中，sockfd的值注定一直在变化，所以maxfd也是需要动态更新
            fd_set rfds;
            FD_ZERO(&rfds);
            int maxfd = _fdarry[0]._fd;
            for (int i = 0; i < N; i++)
            {
                if (_fdarry[i]._fd == defaultfd)
                    continue;
                FD_SET(_fdarry[i]._fd, &rfds);
                if (maxfd < _fdarry[i]._fd)
                    maxfd = _fdarry[i]._fd;
            }
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);
            switch (n)
            {
            case 0:
                LogMessage(Bug, "timeout, %d, %s", errno, strerror(errno));
                break;
            case -1:
                LogMessage(Warring, "select fail, %d, %s", errno, strerror(errno));
                break;
            default:
                LogMessage(Bug, "%d is ready!", n);
                HandlerEvent(rfds);
                PrintFd();
                break;
            }

            sleep(1);
        }
    }

private:
    void HandlerEvent(fd_set rfds)
    {
        for (int i = 0; i < N; i++)
        {
            if (_fdarry[i]._fd == defaultfd)
                continue;
            
            if ((_fdarry[i]._event & FD_READ) && FD_ISSET(_fdarry[i]._fd, &rfds))
            {
                if (_fdarry[i]._fd == _listensock.GetFd())
                {
                    Accepter();
                }
                else if (_fdarry[i]._fd != _listensock.GetFd())
                {
                    ServiceIO(i);
                }
            }

            if ((_fdarry[i]._event & FD_WRITE) && FD_ISSET(_fdarry[i]._fd, &rfds))
            {

            }
        }
    }

    void ServiceIO(int index)
    {
        char buffer[1024];
        int n = recv(_fdarry[index]._fd, buffer, sizeof(buffer), 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::string sendstr = buffer;
            sendstr += "[server]";
            send(_fdarry[index]._fd, sendstr.c_str(), sendstr.size(), 0);
        }
        else
        {
            if (n == 0)
                LogMessage(Bug, "client quit ..., fd: %d", _fdarry[index]);
            else
                LogMessage(Warring, "recv error, %d, %s", errno, strerror(errno));
            close(_fdarry[index]._fd);
            _fdarry[index]._fd = defaultfd;
        }
    }

    void Accepter()
    {
        std::string client_ip;
        uint16_t client_port;
        int fd = _listensock.Accept(&client_ip, &client_port);
        if (fd < 0)
            return;

        LogMessage(Info, "[%s, %d], sock: %d", client_ip.c_str(), client_port, fd);
        int pos = 1;
        for (; pos < N; pos++)
        {
            if (_fdarry[pos]._fd == defaultfd)
                break;
        }

        if (pos == N)
        {
            close(fd);
            LogMessage(Warring, "_fdarray[] full");
        }
        _fdarry[pos]._fd = fd;
        _fdarry[pos]._client_ip = client_ip;
        _fdarry[pos]._client_port = client_port;
        _fdarry[pos]._event = FD_READ;
    }

    void PrintFd()
    {
        std::cout << "_fdarry[]: ";
        for (int i = 0; i < N; i++)
        {
            if (_fdarry[i]._fd == defaultfd)
                continue;
            std::cout << _fdarry[i]._fd << " ";
        }
        std::cout << std::endl;
    }

private:
    Sock _listensock;       // 网络套接字
    uint16_t _port;         // 端口号
    FdEvent _fdarry[N];     // 保存需要监视的文件描述符
};